<template>
  <div class="login-root">
    <div class="login-container">
      <div class="login-header">
        <img src="@/assets/images/logo.svg" alt="Logo" class="logo">
        <h2>欢迎登录</h2>
        <p>请使用邮箱直接登录，未注册账号自动注册</p>
      </div>
      <el-form
          ref="loginform"
          :rules="rules"
          :model="loginform"
          label-width="80px"
          class="login-form"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="loginform.email"
              placeholder="请输入邮箱地址"
              prefix-icon="el-icon-message"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="emailCode">
          <el-input
              v-model="loginform.emailCode"
              placeholder="请输入邮箱验证码"
              prefix-icon="el-icon-lock"
          >
            <template #append>
              <el-button
                  @click="sendEmailCode"
                  :loading="codeLoading"
              >{{ emailMessage }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" icon="el-icon-user-solid" class="login-button"
                     @click="onSubmit" :loading="loginLoading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {emitEvent} from "@/js/EventBus.js";

export default {
  name: "loginUser",

  data() {
    return {
      loginLoading: false,
      codeLoading: false,

      loginform: {
        emailCode: "",
        email: "",
      },

      // 发送验证码的信息提示
      emailMessage: "发送验证码",

      rules: {
        emailCode: [
          {required: true, message: "请输入邮箱验证码", trigger: "blur"},
          {min: 6, max: 6, message: "验证码必须为6位", trigger: "blur"},
        ],
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {type: "email", message: "请输入正确的邮箱地址", trigger: "blur"},
        ],
      },
    };
  },

  methods: {
    // 发送邮箱验证码
    sendEmailCode() {
      if (this.loginform.email.trim() === "") {
        this.$message({
          message: "请输入邮箱",
          type: "error",
        });
        return;
      }
      if (this.$cookie.has("emailCode")) {
        this.$message({
          message: '请勿重复发送验证码',
          type: 'warning'
        });
        return;
      }

      // 发送验证码的间隔时间（s）
      let sendTime = 60;
      this.codeLoading = true;
      // 定时器
      let timer = null;

      this.$api.main.getEmail({
        targetEmail: this.loginform.email.trim(),
        subject: "熊猫工具——登录验证码",
      }).then((res) => {
        this.$message({
          message: res.data.message,
          type: "success",
        });
        this.$cookie.set("emailCode", res.data.data, sendTime * 1000)
        this.codeLoading = false;
        timer = setInterval(() => {
          sendTime--;
          this.emailMessage = `${sendTime}s`;

          if (sendTime <= 0) {
            clearInterval(timer);
            this.emailMessage = '发送验证码';
          }
        }, 1000);
      }).catch(err => {
        console.error(err);
        if (!timer) {
          clearInterval(timer);
        }
        this.codeLoading = false;
        this.emailMessage = '发送验证码';
      });

    },

    // 登录
    async onSubmit() {
      try {
        this.loginLoading = true; // 开始加载

        // 使用Promise形式的validate
        const valid = await this.$refs.loginform.validate();
        if (!valid) {
          console.log("验证失败");
          return;
        }

        // 发送登录请求
        const res = await this.$api.user.loginUser({
          email: this.loginform.email.trim(),
          emailCode: this.loginform.emailCode.trim(),
        });

        // 登录成功处理
        this.$message({
          message: "登录成功",
          type: "success",
          duration: 1000,
          onClose: () => {
            this.$cookie.set("token_expireTime","7 day",this.$sys.token_expireTime)
            emitEvent("closeLogin", {from: "登录成功!"});
            this.loginform = {
              emailCode: "",
              email: "",
            }
          },
        });

        // 存储用户信息
        const data = res.data.data;
        this.$storage.set("token", data.token);

      } catch (err) {
        console.error("登录失败:", err);
        this.loginform.emailCode = ""; // 清空验证码
      } finally {
        this.loginLoading = false; // 无论成功失败，停止加载
      }
    }
  },
};
</script>

<style lang="less" scoped>

.login-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  padding: 40px;
  min-width: 400px;
  animation: fadeInDown 0.5s ease-out;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;

  .logo {
    width: 80px;
    height: 80px;
    transition: transform 0.3s ease;

    &:hover {
      transform: rotate(15deg);
    }
  }

  h2 {
    color: #333;
    margin-bottom: 10px;
  }

  p {
    color: #666;
    font-size: 14px;
  }

}


.login-form {
  /deep/ .el-form-item__label {
    padding-right: 15px;
  }

  /deep/ .el-input-group__append {
    padding: 0 10px;
  }
}

.login-button {
  width: 100%;
  margin-top: 10px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}


.social-login {
  margin-top: 15px;
}

.el-button.circle {
  margin: 0 8px;
  transition: all 0.3s ease;
}

.el-button.circle:hover {
  transform: scale(1.1);
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
